package groupb6.shopsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import groupb6.shopsystem.mapper.*;
import groupb6.shopsystem.pojo.entity.*;
import groupb6.shopsystem.pojo.form.*;
import groupb6.shopsystem.service.SellerService;
import groupb6.shopsystem.util.JWTUtil;
import groupb6.shopsystem.util.enums.OrderStatusEnum;
import groupb6.shopsystem.util.enums.ProductStatusEnum;
import groupb6.shopsystem.util.response.UniversalResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SellerServicelmpl implements SellerService {
    @Autowired
    private OrderProductMapper orderProductMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderProductMapper orderproductMapper;
    @Autowired
    private DestinationMapper destinationMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ReturnMapper returnMapper;
    /**
     * 上架商品
     *
     * @return
     */
    @Override
    public UniversalResponse<Product> AddProduct(Product product) {
        try {
            // 检查产品信息是否完整
            List<String> emptyProperties = new ArrayList<>();

            if (product.getName() == null || product.getName().trim().isEmpty()) {
                emptyProperties.add("name");
            }

            if (product.getImagePath() == null || product.getImagePath().trim().isEmpty()) {
                emptyProperties.add("imagePath");
            }

            if (product.getPrice() == null || product.getPrice() <= 0) {
                emptyProperties.add("price");
            }

            if (product.getType() == null || product.getType().trim().isEmpty()) {
                emptyProperties.add("type");
            }

            if (product.getDetail() == null || product.getDetail().trim().isEmpty()) {
                emptyProperties.add("detail");
            }

            if (!emptyProperties.isEmpty()) {
                // 如果有任何一个字段为空或者价格小于等于0，则返回失败响应
                return new UniversalResponse<>(7005, "以下属性为空或不完整: " + String.join(", ", emptyProperties));
            }
            else {
                // 调用 ProductMapper 中的方法将商品信息插入数据库
                productMapper.insertProduct(product);
                return new UniversalResponse<>(1000, "成功", product);
            }
        } catch (Exception e) {
            // 如果出现异常，返回失败的响应
            return new UniversalResponse<>(1001, "失败");
        }
    }


    /**
     * 下架商品
     *
     * @param productId
     * @return
     */
    @Override
    public UniversalResponse<Product> UnlistProduct(Integer productId) {
        User user = JWTUtil.getCurrentUser();
        Product product = productMapper.getProductById(productId);               // 获取商品信息
        if (product == null) {
            return new UniversalResponse<>(7002, "找不到对应的商品");
        }
        if (!user.getId().equals(product.getSellerId())) {
            return new UniversalResponse<>(2004, "用户权限不足");
        }
        try {
            product.setStatus(ProductStatusEnum.OFF_SHELF.getStatus());
            productMapper.updateById(product);
            return new UniversalResponse<>(1000, "成功", product);
        } catch (Exception e) {
            return new UniversalResponse<>(1001, "失败");
        }
    }

    /**
     * 显示店铺的商品信息
     *
     * @return
     */
    @Override
    public UniversalResponse<List<Product>> showProductsBySellerId() {
        User user = JWTUtil.getCurrentUser();
        // 根据商家 ID 获取对应的所有商品信息
        List<Product> products = productMapper.getProductsBySellerId(user.getId());
        try {
            if (products != null && !products.isEmpty()) {
                // 筛选掉状态为 0 的商品
                List<Product> filteredProducts = new ArrayList<>();
                for (Product product : products) {
                    if (product.getStatus() != 0) {
                        filteredProducts.add(product);
                    }
                }
                if (!filteredProducts.isEmpty()) {
                    // 如果商家有非状态为 0 的商品，则返回成功的响应，包含商品列表
                    return new UniversalResponse<>(1000, "成功", filteredProducts);
                } else {
                    // 如果商家有商品但全部为状态为 0 的商品，则返回失败的响应
                    return new UniversalResponse<>(7003, "还未添加有效商品");
                }
            } else {
                // 如果商家不存在或者商家没有商品，则返回失败的响应
                return new UniversalResponse<>(7003, "还未添加商品");
            }
        } catch (Exception e) {
            return new UniversalResponse<>(1001, "失败");
        }
    }


    /**
     * 显示订单列表
     *
     * @return
     */
    public UniversalResponse<List<OrderWithReturnInfo>> showOrdersBySellerId() {
        User user = JWTUtil.getCurrentUser();
        // 根据商家 ID 获取对应的订单列表
        List<Order> orders = orderMapper.getOrdersBySellerId(user.getId());
        List<OrderWithReturnInfo> orderWithReturnInfos = new ArrayList<>();

        for (Order order : orders) {
            // 严格约束条件: 仅处理状态为1的订单
            if (true) {
                OrderWithReturnInfo orderWithReturnInfo = new OrderWithReturnInfo();
                List<CheckOrderForm> checkOrderForms = new ArrayList<>();

                // 根据订单 ID 获取对应的订单产品列表
                List<Destination> destinations = destinationMapper.getByUser_id(order.getBuyerId());
                if (!destinations.isEmpty()) {
                    Destination selectedDestination = null;
                    if (destinations.size() > 1) {
                        for (Destination destination : destinations) {
                            if (destination.getIsDefault() == 1) {
                                selectedDestination = destination;
                                break;
                            }
                        }
                    }
                    if (selectedDestination == null) {
                        selectedDestination = destinations.get(0);
                    }

                    List<OrderProduct> productsForOrder = orderproductMapper.getOrderProductsByOrderId(order.getId());
                    for (OrderProduct productForOrder : productsForOrder) {
                        Product product = productMapper.getProductById(productForOrder.getProductId());
                        if (product != null) {
                            CheckOrderForm checkOrderForm = new CheckOrderForm();
                            checkOrderForm.setOrderId(order.getId());
                            checkOrderForm.setBuyerId(order.getBuyerId());
                            checkOrderForm.setProductId(product.getId());
                            checkOrderForm.setName(product.getName());
                            checkOrderForm.setImagePath(product.getImagePath());
                            checkOrderForm.setNumber(productForOrder.getNumber());
                            checkOrderForm.setDetail(product.getDetail());
                            checkOrderForm.setPrice(product.getPrice());
                            checkOrderForm.setType(product.getType());
                            checkOrderForm.setOrderTime(order.getOrderTime());
                            checkOrderForm.setStatus(order.getStatus());
                            checkOrderForm.setStatusReturn(order.getStatusReturn());
                            checkOrderForm.setCustomername(selectedDestination.getName());
                            checkOrderForm.setAddress(selectedDestination.getAddress());
                            checkOrderForm.setPhone(selectedDestination.getPhone());
                            checkOrderForms.add(checkOrderForm);
                        }
                    }
                }

                orderWithReturnInfo.setOrderInfo(checkOrderForms);

                // 添加退货信息
                Return returnInfo = returnMapper.getReturnByOrderId(order.getId());
                if (returnInfo != null) {
                    OrderWithReturnInfo.ReturnInfo returnInfoObj = new OrderWithReturnInfo.ReturnInfo();
                    returnInfoObj.setId(returnInfo.getId());
                    returnInfoObj.setStatus(returnInfo.getStatus());
                    returnInfoObj.setRefund(returnInfo.getRefund());
                    returnInfoObj.setDeliverTime(returnInfo.getDeliverTime());
                    returnInfoObj.setFinishTime(returnInfo.getFinishTime());
                    returnInfoObj.setAllowed(returnInfo.getAllowed());
                    returnInfoObj.setReason(returnInfo.getReason());
                    returnInfoObj.setTrackingNumber(returnInfo.getTrackingNumber());
                    orderWithReturnInfo.setReturnInfo(returnInfoObj);
                }

                orderWithReturnInfos.add(orderWithReturnInfo);
            }
        }
        Collections.reverse(orderWithReturnInfos);
        try {
            if (!orderWithReturnInfos.isEmpty()) {
                return new UniversalResponse<>(1000, "成功", orderWithReturnInfos);
            } else {
                return new UniversalResponse<>(7004, "还未创建订单");
            }
        } catch (Exception e) {
            return new UniversalResponse<>(1001, "失败");
        }
    }
    /**
     * 处理订单，仅先实现发货功能
     *
     * @return
     */
    @Override
    public UniversalResponse<Order> ShipOrder(Integer orderId) {
        User user = JWTUtil.getCurrentUser();
        Order order = orderMapper.getOrderByorderId(orderId);
        if (!order.getSellerId().equals(user.getId())) {
            return new UniversalResponse<>(2004, "用户权限不足");
        }
        try {
            if (order.getStatus() == 2) {
                order.setStatus(OrderStatusEnum.SHIPPED.getStatus());
                orderMapper.updateById(order);
                return new UniversalResponse<>(1000, "成功");
            } else {
                if (order.getStatus() == 1)
                    // 如果订单列表为空，则返回失败的响应，表示没有订单
                    return new UniversalResponse<>(3000, "订单还未付款");
                else
                    return new UniversalResponse<>(3004, "订单已发货");
            }
        } catch (Exception e) {
            return new UniversalResponse<>(1001, "失败");
        }
    }


    @Override
    public UniversalResponse<List<Integer>> CheckorderByProductId(Integer productId) {
        try {
            // 查询具有特定产品ID的订单产品列表
            List<OrderProduct> orderProducts = orderProductMapper.selectList(
                    new QueryWrapper<OrderProduct>().eq("product_id", productId)
            );
            if (orderProducts.isEmpty()) {
                return new UniversalResponse<>(7007, "商品可下架");
            }

            // 提取订单ID
            List<Integer> orderIds = new ArrayList<>();
            for (OrderProduct orderProduct : orderProducts) {
                Integer orderId = orderProduct.getOrderId();
                // 查询订单状态是否小于等于2
                Order order = orderMapper.selectById(orderId);
                if (order != null && order.getStatus() <= 2) {
                    orderIds.add(orderId);
                }
                else{
                    return new UniversalResponse<>(7007, "商品可下架");
                }
            }
            return new UniversalResponse<List<Integer>>().ok(orderIds);
        } catch (Exception e) {
            // 处理异常情况并返回错误响应
            return new UniversalResponse<>(1001, "失败");
        }
    }

    /**
     *
     * @param product
     * @return 修改商品信息
     */
    @Override
    public UniversalResponse<List<Product>> ModifyProduct(Product product) {
        User user = JWTUtil.getCurrentUser();
        try {
            // 检查产品信息是否完整
            List<String> emptyProperties = new ArrayList<>();
            if (product.getName() == null || product.getName().trim().isEmpty()) {
                emptyProperties.add("商品名称");
            }
            if (product.getImagePath() == null || product.getImagePath().trim().isEmpty()) {
                emptyProperties.add("图片 URL 链接");
            }
            if (product.getPrice() == null || product.getPrice() <= 0) {
                emptyProperties.add("商品价格");
            }
            if (product.getType() == null || product.getType().trim().isEmpty()) {
                emptyProperties.add("商品类别");
            }
            if (product.getDetail() == null || product.getDetail().trim().isEmpty()) {
                emptyProperties.add("商品详情");
            }
            if (product.getStock() == null || product.getStock() < 0) {
                emptyProperties.add("库存数量");
            }
            if (!emptyProperties.isEmpty()) {
                // 如果有任何一个字段为空或者价格小于等于0，则返回失败响应
                return new UniversalResponse<>(7005, "以下属性为空或不完整: " + String.join(", ", emptyProperties));
            } else {
                // 调用 ProductMapper 中的方法更新商品信息
                productMapper.update(product);
                // 更新成功后，重新查询数据库获取更新后的商品信息
                //List<Product> updatedProducts = productMapper.getProductsBySellerId(user.getId());
                // 返回成功的响应，包含更新后的商品信息列表
                //return new UniversalResponse<>(1000, "成功", updatedProducts);
                return new UniversalResponse<>(1000, "成功");
            }
        } catch (Exception e) {
            // 如果出现异常，返回失败的响应
            return new UniversalResponse<>(1001, "失败");
        }
    }

    @Override
    public UniversalResponse<ModifyProductForm> getProductAttributes(Integer productId) {
        try {
            Product product = productMapper.getProductById(productId);
            if (product == null) {
                return new UniversalResponse<>(7002, "未找到商品信息");
            }

            ModifyProductForm modifyProduct = new ModifyProductForm();
            modifyProduct.setId(product.getId());
            modifyProduct.setName(product.getName());
            modifyProduct.setImagePath(product.getImagePath());
            modifyProduct.setPrice(product.getPrice());
            modifyProduct.setType(product.getType());
            modifyProduct.setStock(product.getStock());
            modifyProduct.setDetail(product.getDetail());

            return new UniversalResponse<>(1000, "成功", modifyProduct);
        } catch (Exception e) {
            return new UniversalResponse<>(1001, "获取商品信息失败");
        }
    }
    @Override
    public UniversalResponse<SearchSellerForm> getSellerInformation(Integer id) {
        try {
            User user = null; // Declare the user variable outside the if blocks

            if (id == -1) {
                user = JWTUtil.getCurrentUser();
            } else if (id != -1) {
                // 使用userMapper从数据库中查询用户信息
                user = userMapper.getUserById(id);
            }
            // 判断用户是否存在
            if (user == null) {
                // 如果未找到用户，构建失败的响应
                return new UniversalResponse<>(1001, "用户不存在", null);
            }
            // 如果身份匹配，构建成功的响应
            SearchSellerForm seller = new SearchSellerForm();
            seller.setId(user.getId());
            seller.setName(user.getName());
            seller.setAvatar(user.getAvatar());
            // 检查商家信息是否完整
            return new UniversalResponse<>(1000, "成功", seller);
        } catch (Exception e) {
            // 捕获异常，返回相应的错误响应
            return new UniversalResponse<>(7002, "获取商家信息失败", null);
        }
    }

//    /**
//     *显示退货列表
//     */
//    @Override
//    public UniversalResponse<List<List<Return>>> showReturn() {
//        User user = JWTUtil.getCurrentUser();
//        List<Order> orders = orderMapper.getOrdersBySellerId(user.getId());
//
//        // 如果订单列表为空，返回尚未生成订单的消息
//        if (orders == null || orders.isEmpty()) {
//            return new UniversalResponse<>(7001, "尚未生成订单");
//        }
//
//        List<Return> returns = new ArrayList<>();
//        for (Order order : orders) {
//            List<Return> orderReturns = returnMapper.getReturnsByOrderId(order.getId());
//            returns.addAll(orderReturns);
//        }
//        try {
//            if (returns != null && !returns.isEmpty()) {
//                // 筛选状态不为5的订单
//                List<Return> filteredReturns = returns.stream()
//                        .filter(return1 -> return1.getStatus() != 5)
//                        .collect(Collectors.toList());
//                if (!filteredReturns.isEmpty()) {
//                    // 根据状态值将退货信息分类
//                    List<Return> status1Returns = filteredReturns.stream()
//                            .filter(return1 -> return1.getStatus() == 1)
//                            .collect(Collectors.toList());
//                    List<Return> status3Returns = filteredReturns.stream()
//                            .filter(return1 -> return1.getStatus() == 3)
//                            .collect(Collectors.toList());
//                    List<Return> status4Returns = filteredReturns.stream()
//                            .filter(return1 -> return1.getStatus() == 4)
//                            .collect(Collectors.toList());
//                    // 将分类后的列表放入外层列表中
//                    List<List<Return>> result = new ArrayList<>();
//                    result.add(status1Returns);
//                    result.add(status3Returns);
//                    result.add(status4Returns);
//                    return new UniversalResponse<>(1000, "成功", result);
//                } else {
//                    return new UniversalResponse<>(7002, "已全部退货成功");
//                }
//            } else {
//                // 如果退货信息列表为空，返回尚未生成退货订单的消息
//                return new UniversalResponse<>(7003, "尚未生成退货订单");
//            }
//        } catch (Exception e) {
//            // 打印异常信息，便于排查问题
//            e.printStackTrace();
//            return new UniversalResponse<>(1001, "失败");
//        }
//    }

    @Override
    public UniversalResponse<Return> AgreeReturnById(HandleReturnForm handle) {
        try {
            // 检查输入的 status 值是否为预期值
            if (handle.getStatus() == 1) {
                // 商家同意退货
                returnMapper.returnAgreeById(handle.getId(), handle.getAllowed());
            } else if (handle.getStatus() == 3) {
                // 商家已到货
                Timestamp finishTime = new Timestamp(System.currentTimeMillis());
                returnMapper.returnReceive(handle.getId(), 5, finishTime);
            } else {
                // 如果 status 值不是预期值，返回错误响应
                return new UniversalResponse<>(1001, "订单状态不匹配");
            }
            // 返回成功信息
            return new UniversalResponse<>(1000, "修改成功");
        } catch (Exception e) {
            // 打印异常信息以进行故障排除
            e.printStackTrace();
            return new UniversalResponse<>(1001, "处理请求时发生错误");
        }
    }


//    @Override
//    public UniversalResponse<Return> ReceiveReturnById(HandleReturnForm handle) {
//        try {
//            // 使用构造函数创建Timestamp对象
//            Timestamp finishTime = new Timestamp(System.currentTimeMillis());
//            // 保存更新后的退货订单信息
//            returnMapper.returnReceive(handle.getId(), handle.getStatus(),finishTime);
//            // 返回成功信息
//            return new UniversalResponse<>(1000, "修改成功");
//        } catch (Exception e) {
//            // 打印异常信息以进行故障排除
//            e.printStackTrace();
//            return new UniversalResponse<>(1001, "操作失败");
//        }
//    }




}
